package cate.game.server.configuration.dao;

import cate.game.role.RolePart;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import easy.java.practice.errorcode.EcException;
import easy.mongo.anno.MgMapField;
import lombok.extern.slf4j.Slf4j;
import org.bson.BsonValue;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.Optional;

@Slf4j
public abstract class MgRolePartDao<T extends RolePart> extends MgRepo<T, String> {

    @Override
    protected <S extends T> Object transId(S entity) {
        try {
            return new ObjectId(entity.uid);
        } catch (Exception e) {
            log.error("entity.uid={}", entity.uid, e);
            return null;
        }
    }

    @Override
    protected <S extends T> void handleAutoId(S entity, BsonValue bv) {
        if(bv == null) {
            //log.info("这家伙是 bv == null");
            return;
        }
        if(bv.isObjectId()) {
            //log.info("这家伙是 isObjectId {}", bv);
            entity.uid = bv.asObjectId().getValue().toHexString();
        } else if(bv.isString()) {
            //log.info("这家伙是 isString {}", bv);
            entity.uid = bv.asString().getValue();
        } else {
            log.error("这家伙是 意料之外 {}", bv);
        }
    }

    @Override
    public Optional<T> findById(String uid) {
        FindIterable<Document> fi = collection.find(Filters.eq(MgMapField.ID, new ObjectId(uid)));
        Document doc = fi.first();
        if(doc == null) {
            return Optional.empty();
        }
        try {
            T entity = getMapper().decode(doc, getEntityClass());
            return Optional.of(entity);
        } catch (Exception e) {
            throw new EcException(e);
        }
    }

    @Override
    public void deleteById(String uid) {
        collection.deleteOne(Filters.eq(MgMapField.ID, new ObjectId(uid)));
    }
}
